package com.huaxindata.im.main.contactview.friend;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseActivity;
import com.huaxindata.im.R;
import com.huaxindata.im.main.chat.ConversationActivity;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.contactview.group.SelectGroupMemberActivity;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.main.menu.SearchContactActivity;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.view.CharBar;
import com.huaxindata.im.view.MessageSearchView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 用于显示联系人、手机通讯录、群组等列表的activity
 * 列表点击功能为如果是本地用户则网络查询是不是注册的企业用户
 * 如果是企业用户可以加为好友，如果不是企业用户可以发送注册邀请
 * 如果是群组则会直接进入聊天界面,如果是好友则会展示好友的资料
 */
public class ContactListActivity extends BaseActivity implements
        AdapterView.OnItemClickListener, AbsListView.OnScrollListener, CharBar.LetterChangeListener {

    private static final String TYPE         = "type";
    public final static  String CH_FRIEND    = "我的好友";
    public final static  String CH_TELEPHONE = "手机通讯录";
    public final static  String CH_GROUP     = "我的群组";
    public final static  String CH_COMPANY   = "企业";
    public static final  String TAG          = "ContactListActivity";
    public static final  int    REQUEST_CODE = 1001;

    String key;
    private Toolbar            mToolbar;
    private ImageView          mAddView;//添加好友按钮
    private ListView           mListView;
    private CharBar            mCharBar;
    private TextView           mCharTipTv;
    private View               mNoDataTipView;
    private TextView           mStickTv;
    private ContactListAdapter mAdapter;

    //数据集声明部分
    private List<Contact>            mContactList;
    private HashMap<String, Integer> mCharIndexMap;

    /**
     * type表示数据类型，0为ContactPerson、1为ContactLocal
     * 2、为ContactGroup、3为公司组织用户
     */
    int type = 0;//0,1,2,3
    MessageSearchView mSearchView;
    Dialog            dialog;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_contact_list;
    }


    @Override
    public void initView() {
        type = getIntent().getIntExtra(TYPE, 0);
        mToolbar = (Toolbar) findViewById(R.id.contact_list_toolbar);
        mAddView = (ImageView) findViewById(R.id.contact_list_toolbar_add);
        mListView = (ListView) findViewById(R.id.contact_list_view);
        mCharBar = (CharBar) findViewById(R.id.contact_list_char_bar);
        mCharTipTv = (TextView) findViewById(R.id.contact_list_char_tip);
        mNoDataTipView = findViewById(R.id.contact_list_empty_tip);
        mStickTv = (TextView) findViewById(R.id.contact_list_stick_tv);
        //将搜索框当作头部加入到ListView中
        mSearchView = (MessageSearchView) LayoutInflater.from(this).inflate(R.layout.search_layout, mListView, false);
        initToolBar();
        mListView.addHeaderView(mSearchView);
        mSearchView.setCallback(new MessageSearchView.Callback() {
            @Override
            public void onTextChanged(CharSequence sequence) {
                //此处是根据搜索时的关键字来过滤要显示的联系人，匹配方法不是很好
                key = sequence.toString();
                initContactData();
            }
        });

        mAdapter = new ContactListAdapter(this);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);
        mCharBar.setTip(mCharTipTv);
        mCharBar.setLetterChangeListener(this);

        mAddView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 0) {
                    Intent intent = new Intent(ContactListActivity.this, SearchContactActivity.class);
                    startActivity(intent);
                } else if (type == 2) {
                    startActivity(new Intent(ContactListActivity.this, SelectGroupMemberActivity.class));
                }
            }
        });

    }


    @Override
    public void initData() {
        initContactData();
    }

    private void initContactData() {
        if (mCharIndexMap == null) {
            mCharIndexMap = new HashMap<>();
        }
        //以下是获取数据部分
        switch (type) {
            case 0:
                mContactList = ContactManager.getFriendList();
                break;
            case 1:
                //此处获取通讯录联系人
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!checkPermission()) {
                        break;
                    }
                }
                mContactList = ContactManager.loadLocalContactList(this);
                break;
            case 2:
                mContactList = ContactManager.getGroupList();
                break;
            case 3:
                mContactList = ContactManager.getColleagueList();
                break;
        }
        if (mContactList == null) {
            mNoDataTipView.setVisibility(View.VISIBLE);
            return;
        }
        List<Object> list = processData();
        mAdapter.setData(list);
    }


    /**
     * 在显示手机通讯录和企业同事时不显示添加好友的菜单
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        if (type == 0) {
            mToolbar.setTitle(CH_FRIEND);
            mSearchView.setTipHint("搜索好友");
            mAddView.setVisibility(View.VISIBLE);
            mAddView.setImageResource(R.mipmap.tianjiahaoyou);
        } else if (type == 1) {
            mToolbar.setTitle(CH_TELEPHONE);
            mAddView.setVisibility(View.GONE);
            mSearchView.setTipHint("搜索手机通讯录");
        } else if (type == 2) {
            mToolbar.setTitle(CH_GROUP);
            mSearchView.setTipHint("群搜索");
            mAddView.setVisibility(View.VISIBLE);
            mAddView.setImageResource(R.mipmap.quntiao);
        } else if (type == 3) {
            final String company;
            if (UserManager.getClientId() == null) {
                company = CH_COMPANY;
            } else {
                company = TextUtils.isEmpty(UserManager.getCompanyName()) ? UserManager.getOrgCode() : UserManager.getCompanyName();
            }
            mToolbar.setTitle(company);
            mAddView.setVisibility(View.GONE);
            mSearchView.setTipHint("搜索组织成员");
        } else {
            finish();
            return;
        }
    }


    /**
     * 此处实现的是一个分组吸顶的效果，根据滑动的第一个可见项
     * 来判断是否更换字母，如果第一个可见的是字母，则更换字母显示
     *
     * @param firstVisibleItem
     */
    private void updateOrClearHeader(int firstVisibleItem) {
        //因为加了头部，所以返回firstVisibleItem=0的时候是头部
        if (firstVisibleItem == 0) {
            mStickTv.setVisibility(View.GONE);
            return;
        }
        final Object o = mAdapter.getData().get(firstVisibleItem - 1);
        if (o instanceof String) {
            mStickTv.setVisibility(View.VISIBLE);
            mStickTv.setText(o.toString());
        }
    }


    /**
     * 对联系人数据进行处理，使数据集合中含有按拼音首字母分组的字符
     *
     * @return
     */
    private List<Object> processData() {
        final List<Object> dataList = new ArrayList<>();
        Collections.sort(mContactList);
        mCharIndexMap.clear();
        for (Contact contact : mContactList) {
            if (!TextUtils.isEmpty(key) && !contact.getNickName().contains(key)) {
                continue;
            }
            //群组用"#"代表
            if (type != 2 && contact instanceof ContactGroup) {
                if (!mCharIndexMap.containsKey("#")) {
                    dataList.add("#");
                    mCharIndexMap.put("#", dataList.size() - 1);
                }
            } else {
                String s = contact.getFirstName();
                if (!mCharIndexMap.containsKey(s)) {
                    dataList.add(s);
                    //记录了某字母首次出现的位置
                    mCharIndexMap.put(s, dataList.size() - 1);
                }
            }
            dataList.add(contact);
        }
        return dataList;
    }

    /**
     * 检查是否有读取联系人权限
     *
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean checkPermission() {
        //申请读取联系人权限
        int permission = checkSelfPermission(Manifest.permission.READ_CONTACTS);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE);
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initContactData();
            }
            Toast.makeText(this, "没有读取联系人权限", Toast.LENGTH_SHORT).show();
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 触摸字母索引的回调方法
     *
     * @param s
     */
    @Override
    public void onLetterChanged(String s) {
        if (mCharIndexMap.containsKey(s)) {
            final int val = mCharIndexMap.get(s);
            mListView.setSelection(val);
            updateOrClearHeader(mListView.getFirstVisiblePosition());
        }
    }

    @Override
    public void onResume() {
        //保证在数据更新前添加observer即可
        ContactManager.addContactRefreshListenner(refreshListener);
        super.onResume();
    }

    @Override
    public void onPause() {
        ContactManager.removeContactRefreshListenner(refreshListener);
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 显示联系人的资料的对话框
     *
     * @param app     :
     * @param contact :
     */
    public void showContactInfo(Activity app, Contact contact) {
       /* ContactInfoDialog contactInfoDialog = new ContactInfoDialog(app);
        contactInfoDialog.setOwnerActivity(app);
        contactInfoDialog.show(contact);*/

        Intent intent = new Intent(app, HxPersonalCenterActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("contact", contact);
        intent.putExtras(bundle);
        ContactListActivity.this.startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        //点击导航栏返回按钮关闭activity
        if (itemId == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 此处需要注意的是由于添加了头部，所以获取数据的时候position要减一
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (type == 1) {//如果是本地联系人，则根据网络查看该联系人是否已经注册过
            List<Object> data = mAdapter.getData();
            if (data.get(position - 1) instanceof String)
                return;
            final Contact contact = (Contact) data.get(position - 1);

            showContactInfo(ContactListActivity.this, contact);

            //根据手机号查询是不是注册过的人，可能是游客或者是企业用户
         /*   Call<UserModel> call = RetrofitClient.getHttpApi().findFriendByPhone(contact.getPhone());
            call.enqueue(new Callback<UserModel>() {
                @Override
                public void onResponse(Call<UserModel> call, Response<UserModel> response) {
                    if (response.isSuccessful()) {
                        UserModel user = response.body();
                        if (user.getState() == 1) {
                            ContactPerson person = user.toPerson();
                            showContactInfo(ContactListActivity.this, person);
                        } else {
                            showContactInfo(ContactListActivity.this, contact);
                        }
                    }
                }

                @Override
                public void onFailure(Call<UserModel> call, Throwable t) {
                    Log.e(TAG, "xxx==查找联系人失败:" + t.getMessage());
                }
            });*/
            return;
        }
        List<Object> data = mAdapter.getData();
        if (data.get(position - 1) instanceof String) {
            return;
        }
        Contact contact = (Contact) data.get(position - 1);
        if (contact instanceof ContactGroup) {
            //如果是群,则直接进入聊天界面
            ContactGroup contactGroup = (ContactGroup) contact;
            ConversationManager.setChatObject(contactGroup);
            Intent intent = new Intent(ContactListActivity.this, ConversationActivity.class);
            startActivity(intent);
        } else {
            showContactInfo(ContactListActivity.this, contact);
        }
        mSearchView.hideSearch();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
            View currentFocus = getCurrentFocus();
            if (currentFocus != null) {
                currentFocus.clearFocus();
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int
            totalItemCount) {
        //在这里实现吸顶效果
        updateOrClearHeader(firstVisibleItem);
    }

    /**
     * 联系人变化了刷新联系人的回调方法
     */
    private ContactManager.OnContactRefresh refreshListener = new ContactManager.OnContactRefresh() {
        @Override
        public void onRefresh() {
            initContactData();
        }
    };
}
